<?php
$read = $_GET['read'];
if(empty($read)) {
    die('无此书籍或已被删除');
}
require('cofd/functions.php');
require('cofd/common.php');
$sql = "SELECT * FROM novel WHERE name ='$read'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) == 0){
    die('无此书籍或已被删除');
    $conn->close();
}
$row = mysqli_fetch_assoc($result);
$directory = $row['zj'];
if($row['refuse'] == 0){
    die('此书籍已被下架或暂未审核（通过）');
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $read; ?>-阅读</title>
    <link rel="stylesheet" href="ast/xsxq.css">
</head>
<body>
    <header>
        <h1 id="bookTitle"><?php echo $read ?></h1>
        <p style="font-size: 1.2em;" id="bookIntroduction"><?php echo $row['content'] ?></p>
    </header>
    <section id="chaptersContainer" class="chapters-container">
        <?php
        $directory2 = explode('/',$directory)[1];
        $ency_novelname = urlencode(encrypt($directory2,'E','xhpayencrypt'));
        if (is_dir($directory)) {
            $files = scandir($directory);
            $files = array_diff($files, array('.', '..'));
            usort($files, function($a, $b) {
                preg_match('/第(\d+)章/', $a, $matchA);
                preg_match('/第(\d+)章/', $b, $matchB);
                if (isset($matchA[1], $matchB[1])) {
                    return intval($matchA[1]) - intval($matchB[1]);
                } else {
                    return strcmp($a, $b);
                }
            });
            foreach ($files as $file) {
                $filePath = $directory . DIRECTORY_SEPARATOR . $file;
                if (is_file($filePath)) {
                    $filename = pathinfo($file, PATHINFO_FILENAME);
                    $filename_en = urlencode(encrypt($filename, 'E', 'xhpayencrypt'));
                    echo "<div class='chapter-item' data-lockm='{$ency_novelname}' data-lockh='{$filename_en}'>
                       {$filename}
                    </div>";
                }
            }
        } else {
            echo "小说异常，请联系管理员解决";
        }
        ?>
    </section>
</body>
</html>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var chapters = document.querySelectorAll('.chapter-item');
    chapters.forEach(function(chapter) {
        chapter.addEventListener('click', function() {
            var lockh = this.getAttribute('data-lockh');
            var lockm = this.getAttribute('data-lockm');
            window.location = 'react.php?novel='+lockm+'&zj='+lockh;
        });
    });
});
</script>
